<?php
if (!defined('ABSPATH')) {
    exit;
}

// 定义主题版本
define('AI_CONTENT_VERSION', '1.0.1');

// 主题设置
function ai_content_setup() {
    // 添加主题支持
    add_theme_support('title-tag');
    add_theme_support('post-thumbnails');
    add_theme_support('automatic-feed-links');
    add_theme_support('html5', array(
        'search-form',
        'comment-form',
        'comment-list',
        'gallery',
        'caption',
    ));
    
    // 注册导航菜单
    register_nav_menus(array(
        'primary' => __('主导航', 'ai-content'),
        'footer' => __('页脚菜单', 'ai-content')
    ));
}
add_action('after_setup_theme', 'ai_content_setup');

// 注册小工具区域
function ai_content_widgets_init() {
    register_sidebar(array(
        'name'          => '主侧边栏',
        'id'            => 'sidebar-1',
        'description'   => '添加小工具到侧边栏',
        'before_widget' => '<div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">',
        'after_widget'  => '</div>',
        'before_title'  => '<div class="p-4 border-b border-gray-100"><h3 class="text-sm font-medium text-gray-900">',
        'after_title'   => '</h3></div>'
    ));
}
add_action('widgets_init', 'ai_content_widgets_init');

/**
 * 修改代码块渲染
 */
function ai_content_code_block_render($content) {
    static $code_counter = 0;
    
    // 修改正则表达式以匹配 WordPress 的代码块
    $pattern = '/<pre><code.*?>(.*?)<\/code><\/pre>|<pre class="wp-block-code"><code>(.*?)<\/code><\/pre>/s';
    
    return preg_replace_callback($pattern, function($matches) use (&$code_counter) {
        $code_counter++;
        // 获取实际的代码内容
        $code = !empty($matches[1]) ? $matches[1] : $matches[2];
        
        // 处理语言标识和路径
        $language = 'plaintext';
        $path = '代码片段';
        
        // 检测语言标记
        if (preg_match('/^```([a-z]+)(?::([^\n]+))?(\n|$)/i', $code, $lang_matches)) {
            $language = $lang_matches[1];
            if (!empty($lang_matches[2])) {
                $path = $lang_matches[2];
            }
            $code = preg_replace('/^```[^\n]*\n/', '', $code);
        }
        
        // 移除可能存在的语言标记
        $code = preg_replace('/^```[a-z]*\n|```$/m', '', $code);
        
        // 构建代码块 HTML
        return sprintf(
            '<div class="wp-block-code">
                <div class="code-header">
                    <span class="code-path">%s</span>
                    <button class="code-copy-button" onclick="copyCodeBlock(%d)">
                        <span class="code-copy-text">复制代码</span>
                    </button>
                </div>
                <pre><code id="code-block-%d" class="language-%s">%s</code></pre>
            </div>',
            esc_html($path),
            $code_counter,
            $code_counter,
            esc_html($language),
            esc_html($code)
        );
    }, $content);
}
add_filter('the_content', 'ai_content_code_block_render', 20);

// 设置默认的文章分数和标签
function ai_content_set_default_scores($post_id) {
    // 只处理文章
    if (get_post_type($post_id) != 'post') {
        return;
    }
    
    // 检查是否已经设置了分数
    $score_fields = array(
        'ai_originality' => 95,
        'ai_practicality' => 90,
        'ai_readability' => 85
    );
    
    foreach ($score_fields as $key => $default_value) {
        $current_value = get_post_meta($post_id, $key, true);
        if (empty($current_value)) {
            update_post_meta($post_id, $key, $default_value);
        }
    }

    // 设置默认标签
    $current_tags = get_post_meta($post_id, 'ai_tags', true);
    if (empty($current_tags)) {
        update_post_meta($post_id, 'ai_tags', array('原创', '高质量'));
    }
}
add_action('save_post', 'ai_content_set_default_scores');

function get_post_length() {
    $content = get_post_field('post_content');
    $word_count = str_word_count(strip_tags($content));
    $minutes = ceil($word_count / 200); // 假设阅读速度为每分钟200字
    return $minutes;
}

// 获取文章阅读量
function get_post_views() {
    $count_key = 'post_views_count';
    $count = get_post_meta(get_the_ID(), $count_key, true);
    if($count == '') {
        delete_post_meta(get_the_ID(), $count_key);
        add_post_meta(get_the_ID(), $count_key, '0');
        return "0";
    }
    return number_format($count);
}

// 设置文章阅读量
function set_post_views() {
    $count_key = 'post_views_count';
    $count = get_post_meta(get_the_ID(), $count_key, true);
    if($count == '') {
        delete_post_meta(get_the_ID(), $count_key);
        add_post_meta(get_the_ID(), $count_key, '1');
    } else {
        $count++;
        update_post_meta(get_the_ID(), $count_key, $count);
    }
}

// 获取 AI 速读量
function get_ai_reads() {
    $count_key = 'post_ai_reads_count';
    $count = get_post_meta(get_the_ID(), $count_key, true);
    if($count == '') {
        delete_post_meta(get_the_ID(), $count_key);
        add_post_meta(get_the_ID(), $count_key, '0');
        return "0";
    }
    return number_format($count);
}

// 设置 AI 速读量
function set_ai_reads() {
    $count_key = 'post_ai_reads_count';
    $count = get_post_meta(get_the_ID(), $count_key, true);
    if($count == '') {
        delete_post_meta(get_the_ID(), $count_key);
        add_post_meta(get_the_ID(), $count_key, '1');
    } else {
        $count++;
        update_post_meta(get_the_ID(), $count_key, $count);
    }
}

// 获取来源网站信息
function get_source_info($source) {
    $sources = array(
        'csdn' => array(
            'name' => 'CSDN',
            'icon' => 'https://g.csdnimg.cn/static/logo/favicon32.ico',
            'classes' => 'bg-[#E01F2B]/10 text-[#E01F2B]'
        ),
        'infoq' => array(
            'name' => 'InfoQ',
            'icon' => 'https://static.infoq.cn/static/infoq/favicon.ico',
            'classes' => 'bg-[#3399ff]/10 text-[#3399ff]'
        ),
        '51cto' => array(
            'name' => '51CTO',
            'icon' => 'https://static.51cto.com/home/web/favicon.ico',
            'classes' => 'bg-[#0089D1]/10 text-[#0089D1]'
        ),
        'xiaohongshu' => array(
            'name' => '小红书',
            'icon' => 'https://www.xiaohongshu.com/favicon.ico',
            'classes' => 'bg-[#FE2C55]/10 text-[#FE2C55]'
        ),
        'toutiao' => array(
            'name' => '今日头条',
            'icon' => 'https://sf3-cdn-tos.douyinstatic.com/obj/eden-cn/pisaxj/toutiao_favicon.ico',
            'classes' => 'bg-[#FF2E4D]/10 text-[#FF2E4D]'
        ),
        'juejin' => array(
            'name' => '掘金',
            'icon' => 'https://lf3-cdn-tos.bytescm.com/obj/static/xitu_juejin_web/static/favicons/favicon-32x32.png',
            'classes' => 'bg-[#1E80FF]/10 text-[#1E80FF]'
        ),
        'zhihu' => array(
            'name' => '知乎',
            'icon' => 'https://static.zhihu.com/heifetz/favicon.ico',
            'classes' => 'bg-[#056DE8]/10 text-[#056DE8]'
        )
    );

    return isset($sources[$source]) ? $sources[$source] : array(
        'name' => '未知来源',
        'icon' => '', // 可以设置一个默认图标
        'classes' => 'bg-gray-100 text-gray-600'
    );
}

// 在文章保存时设置来源（示例）
function set_article_source($post_id) {
    // 这里可以根据实际需求设置文章来源
    // 例如：从文章内容解析，或者通过后台设置
    $sources = array('csdn', 'infoq', '51cto', 'xiaohongshu', 'toutiao', 'juejin', 'zhihu');
    $random_source = $sources[array_rand($sources)];
    update_post_meta($post_id, 'article_source', $random_source);
}
add_action('save_post', 'set_article_source');

// 获取热门 Agent
function get_popular_agents() {
    return array(
        array(
            'name' => 'DeepSeek Coder',
            'description' => '专业的代码助手，支持多种编程语言，代码解释和优化',
            'icon' => 'code-2',
            'gradient' => 'from-purple-500 to-purple-600',
            'type' => '编程开发',
            'tag_class' => 'bg-purple-50 text-purple-600',
            'uses' => 125360,
            'rating' => 4.8,
            'link' => '/agent/deepseek-coder'
        ),
        array(
            'name' => 'Claude 3',
            'description' => '强大的 AI 助手，擅长文本创作、分析和问答',
            'icon' => 'brain',
            'gradient' => 'from-blue-500 to-blue-600',
            'type' => '智能助手',
            'tag_class' => 'bg-blue-50 text-blue-600',
            'uses' => 89750,
            'rating' => 4.9,
            'link' => '/agent/claude-3'
        ),
        array(
            'name' => 'Midjourney',
            'description' => 'AI 绘画和图像生成专家',
            'icon' => 'image',
            'gradient' => 'from-green-500 to-green-600',
            'type' => '图像创作',
            'tag_class' => 'bg-green-50 text-green-600',
            'uses' => 56890,
            'rating' => 4.7,
            'link' => '/agent/midjourney'
        ),
        array(
            'name' => 'GPTs Store',
            'description' => '海量定制 AI 应用市场',
            'icon' => 'store',
            'gradient' => 'from-orange-500 to-orange-600',
            'type' => 'AI 市场',
            'tag_class' => 'bg-orange-50 text-orange-600',
            'uses' => 45670,
            'rating' => 4.6,
            'link' => '/agent/gpts-store'
        )
    );
}

// 获取推荐技术栈
function get_recommended_tech_stacks() {
    return array(
        array(
            'name' => 'Python',
            'icon' => 'code',
            'bg_class' => 'bg-blue-500',
            'link' => '/tech/python'
        ),
        array(
            'name' => 'JavaScript',
            'icon' => 'braces',
            'bg_class' => 'bg-yellow-500',
            'link' => '/tech/javascript'
        ),
        array(
            'name' => 'Docker',
            'icon' => 'container',
            'bg_class' => 'bg-blue-600',
            'link' => '/tech/docker'
        ),
        array(
            'name' => 'React',
            'icon' => 'component',
            'bg_class' => 'bg-cyan-500',
            'link' => '/tech/react'
        )
    );
} 
add_action('save_post', 'set_article_source'); 

// 获取相关文章
function get_related_posts($post_id, $posts_per_page = 3) {
    $categories = wp_get_post_categories($post_id);
    
    return new WP_Query(array(
        'category__in' => $categories,
        'post__not_in' => array($post_id),
        'posts_per_page' => $posts_per_page,
        'orderby' => 'rand'
    ));
} 

/**
 * AI 评分相关函数
 */
function ai_content_get_quality_score($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }
    $score = get_post_meta($post_id, 'ai_quality_score', true);
    return !empty($score) ? intval($score) : 90;
}

function ai_content_get_score_dimensions($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }
    
    return array(
        array(
            'name' => '原创度',
            'score' => intval(get_post_meta($post_id, 'ai_originality_score', true) ?: 85),
            'icon' => 'sparkles'
        ),
        array(
            'name' => '专业度',
            'score' => intval(get_post_meta($post_id, 'ai_professionalism_score', true) ?: 85),
            'icon' => 'book-open'
        ),
        array(
            'name' => '可读性',
            'score' => intval(get_post_meta($post_id, 'ai_readability_score', true) ?: 85),
            'icon' => 'book-open'
        )
    );
}

function ai_content_get_tags($post_id = null) {
    if (!$post_id) {
        $post_id = get_the_ID();
    }
    $tags = get_post_meta($post_id, 'ai_tags', true);
    return $tags ? $tags : array('原创', '高质量');
}

// 添加 Tailwind 基础类到 body
function ai_content_body_classes($classes) {
    $classes[] = 'bg-gray-50';
    return $classes;
}
add_filter('body_class', 'ai_content_body_classes');
